package com.vm.db;

import java.util.ArrayList;
import java.util.List;
import com.vm.model.ShoppingCart;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;

public class ShoppingCartDao {
	private static final String TAG = null;

	public ShoppingCartDao(Context context) {
		if (DBOpenHelper.db == null) {
			new DBOpenHelper(context);
		}
	}

	public synchronized void insert(ShoppingCart shoppingCart) {
		Log.d(TAG, "insert");
		try {
			DBOpenHelper.db
					.execSQL(
							"INSERT INTO shoppingcart(goodsId,name,imageUrl,price,number)VALUES(?,?,?,?,?)",
							new Object[] { shoppingCart.getGoodsId(),
									shoppingCart.getName(),
									shoppingCart.getImageUrl(),
									shoppingCart.getPrice() });
		} catch (Exception e) {
			Log.d(TAG, "insert---" + e.getMessage());
		}
	}

	public synchronized void delete(String goodsId) {
		Log.i(TAG, "delete");
		try {
			DBOpenHelper.db.execSQL("DELETE FROM shoppingcart where goodsId=?",
					new Object[] { goodsId });
		} catch (SQLException e) {
			Log.d(TAG, "delete---" + e.getMessage());
		}
	}

	public synchronized List<ShoppingCart> selectall() {
		Log.d(TAG, "selectall");
		List<ShoppingCart> list = new ArrayList<ShoppingCart>();
		Cursor c = null;
		try {
			c = DBOpenHelper.db.rawQuery("SELECT * FROM shoppingcart", null);
			while (c.moveToNext()) {
				ShoppingCart shoppingCart = new ShoppingCart();
				shoppingCart = new ShoppingCart();
				shoppingCart.setGoodsId(c.getString(0));
				shoppingCart.setName(c.getString(1));
				shoppingCart.setImageUrl(c.getString(2));
				shoppingCart.setPrice(c.getFloat(3));
				shoppingCart.setNumber(c.getInt(4));
				list.add(shoppingCart);
			}
		} catch (SQLException e) {
			Log.d(TAG, "selectall---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return list;
	}

	public boolean ifExits(String goodsId) {
		Log.d(TAG, "ifExists");
		Cursor c = null;
		try {
			c = DBOpenHelper.db.rawQuery(
					"select * from shoppingcart where goodsId=?",
					new String[] { goodsId });
			if (c.moveToNext()) {
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.d(TAG, "ifExists---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return false;

	}
}